package com.liuqianfei.markme.rules.inline;

import com.liuqianfei.markme.core.Token;
import com.liuqianfei.markme.rules.AbstractState;
import com.liuqianfei.markme.rules.IAction;

import java.util.List;

/**
 * Merge adjacent text nodes into one, and re-calculate all token levels
 * @author liuqianfei
 */
public class TextCollapseAction implements IAction
{
    @Override
    public boolean parse(AbstractState state, boolean silent, int startLine, int endLine)
    {
        List<Token> tokens = state.getTokens();
        int curr, last, level = 0, max = tokens.size();

        for (curr = last = 0; curr < max; curr++)
        {
            // re-calculate levels
            level += tokens.get(curr).nesting;
            tokens.get(curr).level = level;

            if ("text".equals(tokens.get(curr).type)
                    && curr + 1 < max
                    && "text".equals(tokens.get(curr + 1).type))
            {
                // collapse two adjacent text nodes
                tokens.get(curr + 1).content = tokens.get(curr).content + tokens.get(curr + 1).content;
            }
            else
            {
                if (curr != last)
                    tokens.set(last, tokens.get(curr));
                last++;
            }
        }

        if (curr != last)
        {
            tokens = tokens.subList(0, last);
            state.setTokens(tokens);
        }

        return true;
    }
}
